package com.thinvent.nj.ais.controller.sys;

import com.alibaba.fastjson.JSONObject;
import com.thinvent.nj.common.rest.ResponseEntity;
import com.thinvent.nj.common.util.EncodeUtil;
import com.thinvent.nj.common.util.MapperUtil;
import com.thinvent.nj.common.util.StringUtil;
import com.thinvent.nj.ais.entity.Org;
import com.thinvent.nj.ais.entity.Role;
import com.thinvent.nj.ais.entity.User;
import com.thinvent.nj.ais.service.UserService;
import com.thinvent.nj.web.controller.BaseViewController;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 用户管理controller
 * @author liupeijun
 */
@Controller
@RequestMapping(path = "/sys/users")
public class UserController extends BaseViewController {

    @Autowired
    private UserService userService;

    @RequiresPermissions("user:view")
    @RequestMapping(method = RequestMethod.GET)
    public String toHtml() {
        return "sys/userList";
    }

    @RequiresPermissions("user:view")
    @RequestMapping(path = "/search/page", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity findTableData(@RequestBody Map<String, Object> params) {
        List<User> targets = userService.findByOrgId(getQueryMsgString(params, "orgId"));
        JSONObject jsonObject = new JSONObject(1);
        jsonObject.put("result", targets);

        return ResponseEntity.ok(jsonObject);
    }

    @RequiresPermissions("user:view")
    @RequestMapping(path = "/{id}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity get(@PathVariable("id") String id) {
        User target = userService.get(id);
        return ResponseEntity.ok(target);
    }

    @RequiresPermissions("user:add")
    @RequestMapping(method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity insert(@RequestBody Map<String, Object> params) {
        User target = new User();
        MapperUtil.copy(params, target);

        target.setPassword(getMsg("defaultUserPwd"));

        setOrgListRoleList(params, target);
        userService.saveUser(target);

        return ResponseEntity.ok();
    }

    private void setOrgListRoleList(Map<String, Object> params, User target) {
        // 所属组织列表
        String[] orgIds = ((String)params.get("orgList")).split(",");
        List<Org> orgs = new ArrayList<>(orgIds.length);
        for(String orgId: orgIds) {
            if (!StringUtil.isNullOrEmpty(orgId)) {
                orgs.add(new Org(orgId));
            }
        }

        target.setOrgList(orgs);

        // 所属角色列表
        String[] roleIds = ((String)params.get("roleList")).split(",");
        List<Role> roles = new ArrayList<>(roleIds.length);
        for(String roleId: roleIds) {
            if (!StringUtil.isNullOrEmpty(roleId)) {
                roles.add(new Role(roleId));
            }
        }

        target.setRoleList(roles);
    }

    @RequiresPermissions("user:update")
    @RequestMapping(path = "/{id}", method = RequestMethod.PUT)
    @ResponseBody
    public ResponseEntity update(@PathVariable("id") String id, @RequestBody Map<String, Object> params) {
        User target = userService.get(id);
        MapperUtil.copy(params, target);

        setOrgListRoleList(params, target);
        userService.saveUser(target);

        return ResponseEntity.ok();
    }

    @RequiresPermissions("user:delete")
    @RequestMapping(path = "/{id}", method = RequestMethod.DELETE)
    @ResponseBody
    public ResponseEntity del(@PathVariable("id") String id) {
        userService.delete(id);
        return ResponseEntity.ok();
    }

    @RequestMapping(path = "/{id}/resetPwd", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity resetPwd(@PathVariable("id") String userId) {
        User user = userService.get(userId);
        user.setPassword(getMsg("defaultUserPwd"));

        userService.update(user);

        return ResponseEntity.ok();
    }

    @RequestMapping(path = "/{id}/changePwd", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity changePwd(@PathVariable("id") String userId, @RequestBody  Map<String, Object> params) {
        User user = userService.get(userId);
        user.setPassword(EncodeUtil.md5((String) params.get("password")));

        userService.update(user);

        return ResponseEntity.ok();
    }
}
